package com.zhisheng.day10_tlias.controller;

import com.zhisheng.day10_tlias.entry.Dept;
import com.zhisheng.day10_tlias.entry.R;
import com.zhisheng.day10_tlias.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.FileNotFoundException;
import java.util.List;

@RestController
@RequestMapping("/depts")
@Slf4j
//@Scope("prototype")
public class DeptController {

    @Autowired
    private DeptService deptService;

    // 查询所有部门的方法
    @GetMapping
    public R<List<Dept>> list(){
            System.out.println(this);
            //int i = 1/0;
            log.info("自定义的日志................................................................");
            // 参  调   响
            List<Dept> list = deptService.list();
            System.out.println(deptService.getClass());
            // 响应
            if(list == null || list.isEmpty()){
                log.info("数据库无数据..............");
               return    R.fail("亲,暂无数据,请先添加...");
            }
            return R.success(list);

    }

    // 根据id删除部门
    @DeleteMapping("{id}")
    public R<String> delById(@PathVariable Integer id) throws FileNotFoundException {
        log.info("controller中根据 {} 删除数据的方法执行了...........................................",id);
        int i = deptService.delById(id);
        if(i >= 1){
            return R.success(null);
        }
        return R.fail("删除失败....");
    }

    // 根据id查询部门对象,目的是为了用户点击"编辑"按钮的时候,回显页面上的数据
    @GetMapping("{id}")
    public R<Dept> getById(@PathVariable Integer id){
        Dept dept = deptService.getById(id);
        if(dept != null){
            return R.success(dept);
        }
        return R.fail("根据id查询失败....");
    }
    // 根据id真正的修改数据库
    @PutMapping
    public R<String> updateById(@RequestBody Dept dept){
       int i = deptService.updateById(dept);
        if(i >= 1){
            return R.success(null);
        }
        return R.fail("删除失败....");
    }

    // 添加部门
    @PostMapping
    public R<String> insert(@RequestBody Dept dept){
        int i = deptService.insert(dept);
        if(i >= 1){
            return R.success(null);
        }
        return R.fail("删除失败....");
    }

}
